All files / middleware resourceLimits.js

0% Statements 0/47
0% Branches 0/24
0% Functions 0/4
0% Lines 0/47

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210                                                                                                                                                                                                                                                                                                                                                                                                                                   
/**
 * Resource Limits Middleware
 * Validates if tenant can create more resources based on their plan limits
 */
 
const { pool } = require('../config/database');
const { logger } = require('../config/logger');
 
/**
 * Check if tenant has reached resource limit
 * @param {string} resourceType - Type of resource (stores, users, departments, contacts, conversations, devices)
 */
const checkResourceLimit = (resourceType) => {
  return async (req, res, next) => {
    try {
      const tenantId = req.tenantId || req.user?.tenantId || req.user?.tenant_id;
 
      if (!tenantId) {
        return res.status(400).json({
          success: false,
          message: 'Tenant ID not found'
        });
      }
 
      // Get tenant limits
      const [tenants] = await pool.execute(
        'SELECT * FROM tenants WHERE id = ?',
        [tenantId]
      );
 
      if (tenants.length === 0) {
        return res.status(404).json({
          success: false,
          message: 'Tenant not found'
        });
      }
 
      const tenant = tenants[0];
 
      // Map resource types to limit columns and table names
      const resourceConfig = {
        stores: {
          limitColumn: 'max_stores',
          table: 'stores',
          name: 'stores'
        },
        users: {
          limitColumn: 'max_users',
          table: 'users',
          name: 'users'
        },
        departments: {
          limitColumn: 'max_departments',
          table: 'departments',
          name: 'departments'
        },
        contacts: {
          limitColumn: 'max_contacts',
          table: 'contacts',
          name: 'contacts'
        },
        conversations: {
          limitColumn: 'max_conversations',
          table: 'conversations',
          name: 'conversations'
        },
        devices: {
          limitColumn: 'max_devices',
          table: 'devices',
          name: 'devices'
        }
      };
 
      const config = resourceConfig[resourceType];
 
      if (!config) {
        logger.error('Invalid resource type', { resourceType });
        return res.status(400).json({
          success: false,
          message: 'Invalid resource type'
        });
      }
 
      const limit = tenant[config.limitColumn];
 
      // If limit is -1 or null, it's unlimited
      if (limit === -1 || limit === null) {
        return next();
      }
 
      // Check current usage
      const [result] = await pool.execute(
        `SELECT COUNT(*) as count FROM ${config.table} WHERE tenant_id = ?`,
        [tenantId]
      );
 
      const currentCount = result[0].count;
 
      if (currentCount >= limit) {
        logger.warn('Resource limit reached', {
          tenantId,
          resourceType,
          currentCount,
          limit
        });
 
        return res.status(403).json({
          success: false,
          message: `You have reached the maximum number of ${config.name} (${limit}) allowed by your plan. Please upgrade your plan to add more.`,
          error: 'RESOURCE_LIMIT_REACHED',
          data: {
            resource: resourceType,
            current: currentCount,
            limit: limit
          }
        });
      }
 
      // Add limit info to request for reference
      req.resourceLimit = {
        resource: resourceType,
        current: currentCount,
        limit: limit,
        remaining: limit - currentCount
      };
 
      next();
    } catch (error) {
      logger.error('Error checking resource limit', {
        error: error.message,
        resourceType
      });
      return res.status(500).json({
        success: false,
        message: 'Error checking resource limits'
      });
    }
  };
};
 
/**
 * Check if feature is enabled for tenant's plan
 * @param {string} featureName - Name of the feature (whatsapp_enabled, ai_enabled, etc.)
 */
const checkFeatureEnabled = (featureName) => {
  return async (req, res, next) => {
    try {
      const tenantId = req.tenantId || req.user?.tenantId || req.user?.tenant_id;
 
      if (!tenantId) {
        return res.status(400).json({
          success: false,
          message: 'Tenant ID not found'
        });
      }
 
      // Get tenant plan features
      const [tenants] = await pool.execute(
        `SELECT t.*, sp.${featureName}
         FROM tenants t
         LEFT JOIN subscription_plans sp ON t.plan_id = sp.id
         WHERE t.id = ?`,
        [tenantId]
      );
 
      if (tenants.length === 0) {
        return res.status(404).json({
          success: false,
          message: 'Tenant not found'
        });
      }
 
      const tenant = tenants[0];
      const isEnabled = tenant[featureName];
 
      if (!isEnabled) {
        logger.warn('Feature not enabled for tenant', {
          tenantId,
          featureName
        });
 
        return res.status(403).json({
          success: false,
          message: `This feature is not available in your current plan. Please upgrade to access ${featureName.replace('_enabled', '').replace('_', ' ')}.`,
          error: 'FEATURE_NOT_ENABLED',
          data: {
            feature: featureName
          }
        });
      }
 
      next();
    } catch (error) {
      logger.error('Error checking feature access', {
        error: error.message,
        featureName
      });
      return res.status(500).json({
        success: false,
        message: 'Error checking feature access'
      });
    }
  };
};
 
module.exports = {
  checkResourceLimit,
  checkFeatureEnabled
};